﻿/****************************************************************************
*                                                                           *
* Copyright (c) Ionescu M. Marius. All rights reserved(2010).               *
*                                                                           *
****************************************************************************/

using System;
using System.Collections.Specialized;
using System.Data;
using System.Linq;
using System.Web.UI;
using System.Web.UI.WebControls;
using AjaxControlToolkit;

/// <summary>
/// Summary description for MyTemplate
/// </summary>
public class MyTemplate : IBindableTemplate
{
	private string column_type;
	private string column_values;
	private string column_name;
	private string column_defaultValue;
	private string column_minValue;
	private string column_maxValue;
	private string column_required;

	private Control m_container;
	protected string m_strDateFormat = Tools.GetDateFormat();

	public MyTemplate(string column_type, string column_values, string column_name, string column_defaultValue, string column_minValue, string column_maxValue, string column_required)
	{
		this.column_type = column_type;
		this.column_values = column_values;
		this.column_name = column_name;
		this.column_defaultValue = column_defaultValue;
		this.column_minValue = column_minValue;
		this.column_maxValue = column_maxValue;
		this.column_required = column_required;
	}

	public void InstantiateIn(Control container)
	{
		m_container = container;
		RangeValidator rangeVal = null;
		RangeValidator rangeVal_date = null;

		#region SwitchColumn_type
		switch (column_type)
		{
			case "1":
				{
					TextBox text_type = new TextBox();
					text_type.ID = "text_type_" + column_name;
					text_type.DataBinding += new EventHandler(this.OnDataBinding);
					container.Controls.Add(text_type);
					// required field
					//if (column_required == "True")
					//{
					//    RequiredFieldValidator text_required = new RequiredFieldValidator();
					//    text_required.ID = "text_required" + column_name;
					//    text_required.ControlToValidate = text_type.ID;
					//    text_required.Display = ValidatorDisplay.Dynamic;
					//    text_required.ErrorMessage = "*";
					//    text_required.ValidationGroup = "ValidationGroup_Questionnaire";
					//    container.Controls.Add(text_required);
					//}
				}
				break;
			case "2":
				{
					TextBox date_type = new TextBox();
					date_type.ID = "data_type_" + column_name;

					Image calendar_button = new Image();
					CalendarExtender calendar_type = new CalendarExtender();
					MaskedEditExtender calendar_mask = new MaskedEditExtender();
					MaskedEditValidator calendar_validator = new MaskedEditValidator();

					calendar_button.ID = "calendar_button_" + column_name;
					calendar_button.ImageUrl = "~/Images/Calendar_scheduleHS.png";
					calendar_button.AlternateText = "Click to show calendar";
					calendar_button.Style.Add("cursor", "pointer");

					calendar_type.ID = "calendar_type_" + column_name;
					calendar_type.TargetControlID = date_type.ID;
					calendar_type.Format = m_strDateFormat;
					calendar_type.PopupButtonID = calendar_button.ID;

					calendar_mask.ID = "calendar_mask_" + column_name;
					calendar_mask.TargetControlID = date_type.ID;
					calendar_mask.Mask = "99/99/9999";
					calendar_mask.MessageValidatorTip = true;
					calendar_mask.OnFocusCssClass = "MaskedEditFocus";
					calendar_mask.OnInvalidCssClass = "MaskedEditError";
					calendar_mask.MaskType = MaskedEditType.Date;
					calendar_mask.ErrorTooltipEnabled = false;

					calendar_validator.ID = "calendar_validator_" + column_name;
					calendar_validator.ControlExtender = calendar_mask.ID;
					calendar_validator.ControlToValidate = date_type.ID;
					calendar_validator.Display = ValidatorDisplay.Dynamic;
					calendar_validator.TooltipMessage = "*";
					calendar_validator.EmptyValueBlurredText = "*";
					calendar_validator.InvalidValueBlurredMessage = "*";
					calendar_validator.ValidationGroup = "ValidationGroup_Questionnaire";

					date_type.DataBinding += new EventHandler(this.OnDataBinding);

					container.Controls.Add(date_type);
					container.Controls.Add(calendar_type);
					container.Controls.Add(calendar_button);
					container.Controls.Add(calendar_mask);
					container.Controls.Add(calendar_validator);

					rangeVal_date = new RangeValidator();
					rangeVal_date.ValidationGroup = "ValidationGroup_Questionnaire";
					if (column_maxValue == "")
						rangeVal_date.ErrorMessage = string.Format(Resources.DatabaseStrings.HigherDate, column_minValue);
					else
					{
						if (column_minValue == "")
							rangeVal_date.ErrorMessage = string.Format(Resources.DatabaseStrings.LowerDate, column_maxValue);
						else
							rangeVal_date.ErrorMessage = string.Format(Resources.DatabaseStrings.BetweenDate, column_minValue, column_maxValue);
					}

					if ((column_minValue == "")) column_minValue = (new DateTime(1900, 1, 1)).ToString("yyyy-MM-dd");

					if ((column_maxValue == "")) column_maxValue = (new DateTime(2079, 1, 1)).ToString("yyyy-MM-dd");


					rangeVal_date.ControlToValidate = date_type.ID;
					rangeVal_date.MaximumValue = column_maxValue;
					rangeVal_date.MinimumValue = column_minValue;
					rangeVal_date.Display = ValidatorDisplay.Dynamic;
					rangeVal_date.Text = "*";
					rangeVal_date.ID = "range_" + column_name;

					rangeVal_date.Type = ValidationDataType.Date;
					container.Controls.Add(rangeVal_date);

					ValidatorCalloutExtender rangeVal_date_extender = new ValidatorCalloutExtender();
					rangeVal_date_extender.ID = "rangeVal_date_extender_" + column_name;
					rangeVal_date_extender.TargetControlID = rangeVal_date.ID;
					container.Controls.Add(rangeVal_date_extender);

					// required field
					//if (column_required == "True")
					//{
					//    RequiredFieldValidator data_required = new RequiredFieldValidator();
					//    data_required.ID = "data_required" + column_name;
					//    data_required.ControlToValidate = date_type.ID;
					//    data_required.Display = ValidatorDisplay.Dynamic;
					//    data_required.ErrorMessage = "*";
					//    data_required.ValidationGroup = "ValidationGroup_Questionnaire";
					//    container.Controls.Add(data_required);
					//}
				}
				break;
			case "3":
				{
					CheckBox check_type = new CheckBox();
					check_type.ID = "check_type_" + column_name;
					check_type.DataBinding += new EventHandler(this.OnDataBinding);
					container.Controls.Add(check_type);

					////required field
					//if (column_required == "True")
					//{
					//    RequiredFieldValidator check_required = new RequiredFieldValidator();
					//    check_required.ID = "check_required" + column_name;
					//    check_required.ControlToValidate = check_type.ID;
					//    check_required.Display = ValidatorDisplay.Dynamic;
					//    check_required.ErrorMessage = "*";
					//    check_required.ValidationGroup = "ValidationGroup_Questionnaire";
					//    container.Controls.Add(check_required);
					//}
				}
				break;
			case "4":
				{
					RadioButtonList radio_type = new RadioButtonList();
					radio_type.ID = "radio_type_" + column_name;
					radio_type.RepeatColumns = 3;
					radio_type.DataSource = column_values.Replace("\r", "").Split(new char[] { '\n' });
					radio_type.DataBinding += new EventHandler(this.OnDataBinding);
					container.Controls.Add(radio_type);
					radio_type.DataBind();

					//required field
					//if (column_required == "True")
					//{
					//    RequiredFieldValidator radio_required = new RequiredFieldValidator();
					//    radio_required.ID = "radio_required" + column_name;
					//    radio_required.ControlToValidate = radio_type.ID;
					//    radio_required.Display = ValidatorDisplay.Dynamic;
					//    radio_required.ErrorMessage = "*";
					//    radio_required.ValidationGroup = "ValidationGroup_Questionnaire";
					//    container.Controls.Add(radio_required);
					//}
				}
				break;
			case "5":
				{
					DropDownList list_type = new DropDownList();
					list_type.ID = "list_type_" + column_name;
					list_type.DataSource = column_values.Replace("\r", "").Split(new char[] { '\n' });
					list_type.DataBinding += new EventHandler(this.OnDataBinding);
					container.Controls.Add(list_type);
					list_type.DataBind();

					//required field
					//if (column_required == "True")
					//{
					//    RequiredFieldValidator list_required = new RequiredFieldValidator();
					//    list_required.ID = "list_required" + column_name;
					//    list_required.ControlToValidate = list_type.ID;
					//    list_required.Display = ValidatorDisplay.Dynamic;
					//    list_required.ErrorMessage = "*";
					//    list_required.ValidationGroup = "ValidationGroup_Questionnaire";
					//    container.Controls.Add(list_required);
					//}
				}
				break;
			case "6":
				{
					TextBox numeric_type = new TextBox();
					numeric_type.ID = "txt_" + column_name;
					numeric_type.DataBinding += new EventHandler(this.OnDataBinding);
					container.Controls.Add(numeric_type);

					rangeVal = new RangeValidator();
					rangeVal.ValidationGroup = "ValidationGroup_Questionnaire";


					if ((column_maxValue == "") && (column_minValue != ""))
						rangeVal.ErrorMessage = string.Format(Resources.DatabaseStrings.HigherValue, column_minValue);
					else
					{
						if (column_minValue == "")
							rangeVal.ErrorMessage = string.Format(Resources.DatabaseStrings.LowerValue, column_maxValue);
						else
							rangeVal.ErrorMessage = string.Format(Resources.DatabaseStrings.BetweenValue, column_minValue, column_maxValue);

					}

					if ((column_minValue == "")) column_minValue = Int32.MinValue.ToString();

					if ((column_maxValue == "")) column_maxValue = Int32.MaxValue.ToString();


					rangeVal.ControlToValidate = numeric_type.ID;
					rangeVal.MaximumValue = column_maxValue;
					rangeVal.MinimumValue = column_minValue;
					rangeVal.Display = ValidatorDisplay.Dynamic;
					rangeVal.Text = "*";
					rangeVal.ID = "range_" + column_name;

					rangeVal.Type = ValidationDataType.Double;
					container.Controls.Add(rangeVal);

					ValidatorCalloutExtender rangeVal_extender = new ValidatorCalloutExtender();
					rangeVal_extender.ID = "rangeVal_extender_" + column_name;
					rangeVal_extender.TargetControlID = rangeVal.ID;
					container.Controls.Add(rangeVal_extender);

					FilteredTextBoxExtender only_numeric = new FilteredTextBoxExtender();
					only_numeric.ID = "only_numeric_" + column_name;
					only_numeric.TargetControlID = numeric_type.ID;
					only_numeric.ValidChars = "-0123456789,.";
					container.Controls.Add(only_numeric);

					//required field
					//if (column_required == "True")
					//{
					//    RequiredFieldValidator numeric_required = new RequiredFieldValidator();
					//    numeric_required.ID = "numeric_required" + column_name;
					//    numeric_required.ControlToValidate = numeric_type.ID;
					//    numeric_required.Display = ValidatorDisplay.Dynamic;
					//    numeric_required.ErrorMessage = "*";
					//    numeric_required.ValidationGroup = "ValidationGroup_Questionnaire";
					//    container.Controls.Add(numeric_required);
					//}
				}
				break;
		#endregion SwitchColumn_type



		}
	}

	public void OnDataBinding(object sender, EventArgs e)
	{
		switch (column_type)
		{
			case "1":
				{
					TextBox text_type = (TextBox)sender;
					GridViewRow container = (GridViewRow)text_type.NamingContainer;

					if (((DataRowView)container.DataItem)[column_name] == System.DBNull.Value || ((DataRowView)container.DataItem)[column_name].ToString() == "")
						((DataRowView)container.DataItem)[column_name] = column_defaultValue;

					if (((DataRowView)container.DataItem)[column_name] != System.DBNull.Value)
						text_type.Text = ((DataRowView)container.DataItem)[column_name].ToString();
				}
				break;
			case "2":
				{
					TextBox data_type = (TextBox)sender;
					//data_type.ID = "data_type_" + column_name;

					GridViewRow container = (GridViewRow)data_type.NamingContainer;

					if (((DataRowView)container.DataItem)[column_name] == System.DBNull.Value || ((DataRowView)container.DataItem)[column_name].ToString() == "")
						((DataRowView)container.DataItem)[column_name] = Tools.GetDateInLocalFormat(column_defaultValue);

					string aa = "";
					if (((DataRowView)container.DataItem)[column_name] != System.DBNull.Value)
						aa = Tools.GetDateInLocalFormat(((DataRowView)container.DataItem)[column_name].ToString());

					DateTime date;
					if (DateTime.TryParse(aa, out date))
						data_type.Text = date.ToString();
				}
				break;
			case "3":
				{
					CheckBox check_type = (CheckBox)sender;
					GridViewRow container = (GridViewRow)check_type.NamingContainer;

					if (((DataRowView)container.DataItem)[column_name] == System.DBNull.Value || ((DataRowView)container.DataItem)[column_name].ToString() == "")
						((DataRowView)container.DataItem)[column_name] = column_defaultValue;

					string aa = "";
					if (((DataRowView)container.DataItem)[column_name] != System.DBNull.Value)
						aa = ((DataRowView)container.DataItem)[column_name].ToString();

					bool b;
					if (bool.TryParse(aa, out b))
						check_type.Checked = b;
				}
				break;
			case "4":
				{
					RadioButtonList radio_type = (RadioButtonList)sender;
					GridViewRow container = (GridViewRow)radio_type.NamingContainer;

					if (container != null)
					{
						if (((DataRowView)container.DataItem)[column_name] == System.DBNull.Value || ((DataRowView)container.DataItem)[column_name].ToString() == "")
							((DataRowView)container.DataItem)[column_name] = column_defaultValue;

						string aa = "";
						if (((DataRowView)container.DataItem)[column_name] != System.DBNull.Value)
							aa = ((DataRowView)container.DataItem)[column_name].ToString();
						if (aa == "")
							aa = column_defaultValue;
						if (column_values.Replace("\r", "").Split(new char[] { '\n' }).Contains(aa))
							radio_type.SelectedValue = aa;
					}
				}
				break;
			case "5":
				{
					DropDownList list_type = (DropDownList)sender;
					GridViewRow container = (GridViewRow)list_type.NamingContainer;

					if (container != null)
					{
						DataRowView drv = ((DataRowView)container.DataItem);
						if (drv[column_name] == System.DBNull.Value || drv[column_name].ToString() == "")
						{
							if (column_defaultValue == "")
							{
								string[] bb = column_values.Replace("\r", "").Split(new char[] { '\n' });
								if (bb.Length > 0)
									drv[column_name] = bb[0];
							}
							else
								drv[column_name] = column_defaultValue;
						}

						string aa = "";
						if (drv[column_name] != System.DBNull.Value)
							aa = drv[column_name].ToString();
						if (aa == "" && column_defaultValue != "")
							aa = column_defaultValue;
						if (column_values.Replace("\r", "").Split(new char[] { '\n' }).Contains(aa))
							list_type.SelectedValue = aa;
					}
				}
				break;
			case "6":
				{
					TextBox numeric_type = (TextBox)sender;
					GridViewRow container = (GridViewRow)numeric_type.NamingContainer;

					if (((DataRowView)container.DataItem)[column_name] == System.DBNull.Value || ((DataRowView)container.DataItem)[column_name].ToString() == "")
						((DataRowView)container.DataItem)[column_name] = Tools.GetNumberInLocalFormat(column_defaultValue);

					if (((DataRowView)container.DataItem)[column_name] != System.DBNull.Value)
						numeric_type.Text = Tools.GetNumberInLocalFormat(((DataRowView)container.DataItem)[column_name].ToString());
				}
				break;
			default:
				break;
		}

	}

	public IOrderedDictionary ExtractValues(Control container)
	{
		TableCell tc = null;
		foreach (TableCell c in (container as GridViewRow).Cells)
		{
			if (c is DataControlFieldCell && ((DataControlFieldCell)c).ContainingField is TemplateField)
			{
				ITemplate t = ((TemplateField)((DataControlFieldCell)c).ContainingField).ItemTemplate;
				if (t is MyTemplate && (MyTemplate)t == this)
				{
					tc = c;
					break;
				}
			}
		}
		OrderedDictionary dict = new OrderedDictionary();
		switch (column_type)
		{
			case "1":
				{
					string text_value = ((TextBox)tc.Controls[0]).Text;
					if (text_value != "")
						dict.Add(this.column_name, text_value);
					else
						dict.Add(this.column_name, System.DBNull.Value);
				}
				break;
			case "2":
				{
					string data_value = Tools.GetDateInEnglishFormat(((TextBox)tc.Controls[0]).Text);
					if (data_value != "")
						dict.Add(this.column_name, data_value);
					else
						dict.Add(this.column_name, System.DBNull.Value);
				}
				break;
			case "3":
				{
					bool check_value = ((CheckBox)tc.Controls[0]).Checked;
					dict.Add(this.column_name, check_value);
				}
				break;
			case "4":
				{
					string radio_value = ((RadioButtonList)tc.Controls[0]).SelectedValue;
					if (radio_value != "")
						dict.Add(this.column_name, radio_value);
					else
						dict.Add(this.column_name, System.DBNull.Value);
				}
				break;
			case "5":
				{
					string list_value = ((DropDownList)tc.Controls[0]).SelectedValue;
					if (list_value != "")
						dict.Add(this.column_name, list_value);
					else
						dict.Add(this.column_name, System.DBNull.Value);
				}
				break;
			case "6":
				{
					string numeric_value = Tools.GetNumberInEnglishFormat(((TextBox)tc.Controls[0]).Text);
					if (numeric_value != "")
						dict.Add(this.column_name, numeric_value);
					else
						dict.Add(this.column_name, System.DBNull.Value);
				}
				break;
			default:
				break;
		}
		return dict;

	}
}
